import requests
from bs4 import BeautifulSoup
import time

BASE_URL = "http://www.air-level.com"
HEADERS = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'}
REQUEST_TIMEOUT = 10
DELAY = 1  # 请求间隔防止反爬


def get_all_cities():
    """获取所有城市名称与链接的映射关系"""
    city_dict = {}
    try:
        response = requests.get(BASE_URL, headers=HEADERS, timeout=REQUEST_TIMEOUT)
        response.raise_for_status()
        soup = BeautifulSoup(response.text, "html.parser")

        # 获取城市列表
        city_links = soup.select('#citylist a')
        for link in city_links:
            city_name = link.get_text(strip=True)
            city_url = link['href']
            city_dict[city_name] = city_url

    except Exception as e:
        print(f"获取城市列表失败：{str(e)}")
    return city_dict


def get_aqi_by_city(city_url):
    """根据城市链接获取AQI数据"""
    full_url = BASE_URL + city_url
    try:
        time.sleep(DELAY)
        response = requests.get(full_url, headers=HEADERS, timeout=REQUEST_TIMEOUT)
        response.raise_for_status()

        soup = BeautifulSoup(response.text, "html.parser")
        aqi_span = soup.find("span")

        if aqi_span and aqi_span.string:
            return aqi_span.string.strip()
        return "数据解析失败"

    except requests.exceptions.HTTPError as e:
        return f"HTTP错误 {e.response.status_code}"
    except Exception as e:
        print(f"发生异常：{str(e)}")
        return "获取失败"


def main():
    # 获取城市字典
    city_dict = get_all_cities()
    if not city_dict:
        print("无法获取城市列表，请检查网络连接")
        return

    while True:
        print("\n请输入要查询的城市名称（输入q退出）：")
        user_input = input().strip()

        if user_input.lower() == 'q':
            print("感谢使用，再见！")
            break

        # 查找匹配的城市
        matched = False
        for city_name, city_url in city_dict.items():
            if user_input in city_name:  # 支持模糊匹配
                aqi = get_aqi_by_city(city_url)
                print(f"\n{city_name} 的空气质量指数(AQI)为：{aqi}")
                matched = True

        if not matched:
            print(f"未找到与'{user_input}'相关的城市，请检查输入是否正确")
            print("支持的城市列表：")
            print(", ".join(city_dict.keys()))


if __name__ == "__main__":
    print("=== 城市空气质量查询系统 ===")
    main()